package com.sdp.right.flow;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import bsh.Interpreter;

public class FlowConditionParse {

	public static void main(String[] args) {
        // 定义要执行的字符串代码
        String content = "return {pass}==0 && {pass1}==1;";
        Map<String,String> param = new HashMap<String, String>();
        param.put("pass", "0");
        param.put("pass1", "1");
        
        // 执行字符串代码
        System.out.println(parse(content, param));
       
        
	}
	
	public static boolean parse(String conditon,Map<String,String> variable) {
		// 创建一个BeanShell解释器实例
        Interpreter interpreter = new Interpreter();
        boolean flag = true;
        try {
        	Pattern pattern = Pattern.compile("\\{([^\\}]+)\\}");
	        Matcher matcher = pattern.matcher(conditon);
	        StringBuffer sbf = new StringBuffer("");
	        while (matcher.find()) {
	        	String key = matcher.group(1);
	        	String val = variable.get(key);
	        	matcher.appendReplacement(sbf, val==null?"":val);
	        }
	        matcher.appendTail(sbf);
	        Object result = interpreter.eval(sbf.toString());
	        if(result.toString().equals("true")) {
	        	flag = true;
	        }else {
	        	flag = false;
	        }
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
        return flag;
	}
	
}
